package member.base.util;

import m.common.model.util.ModelQueryList;
import m.server.web.AuthInfoUtil;
import m.server.web.Cookie;
import m.system.RuntimeData;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.ArrayUtil;
import m.system.util.DateUtil;
import m.system.util.ObjectUtil;
import member.base.model.BusinessInfo;
import member.base.model.StoreInfo;
import member.base.model.UserInfo;
import member.base.service.UserInfoService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PowerUtil {
    private static final Map<String,UserInfo> userMap=new HashMap<>();

    /**
     * 重置用户信息
     */
    public static void resetUser(Object userOid){
        userMap.remove(userOid);
    }
    /**
     * 登录设置当前用户
     */
    public static void setUser(Object userOid){
        CacheUtil.push(AuthInfoUtil.getSession()+"_login",userOid);
    }
    /**
     * 获取当前登录用户 未登录则抛异常
     */
    public static UserInfo getUser() throws Exception {
        return getUser(true);
    }
    /**
     * 获取当前登录用户 isThrow
     */
    public static UserInfo getUser(boolean isThrow) throws Exception {
        Object user=CacheUtil.get(AuthInfoUtil.getSession()+"_login");
        if(null==user){
            Cookie token=AuthInfoUtil.getRequest().getCookie("user_token");
            if(null!=token){
                user= RuntimeData.getService(UserInfoService.class).getUserOidByToken(token.getValue());
            }
            if(null!=user) setUser(user);
        }
        if(null==user){
            if(isThrow) throw new MException("用户未登录");
            else return null;
        }else{
            String oid=(String) user;
            if(null==userMap.get(oid)){
                userMap.put(oid, ModelQueryList.getModel(UserInfo.class,oid,"*"));
            }
            return userMap.get(oid);
        }
    }

    /**
     * 退出当前用户
     */
    public static String clearUser(){
        Object user=CacheUtil.get(AuthInfoUtil.getSession()+"_login");
        CacheUtil.clear(AuthInfoUtil.getSession()+"_login");
        if(null!=user){
            resetUser(user);
            return (String) user;
        }else {
            return null;
        }
    }

    /**
     * 获取当前登录商家
     */
    public static BusinessInfo getBusiness() throws Exception {
        return getBusiness(true);
    }
    /**
     * 获取当前登录商家
     */
    public static BusinessInfo getBusiness(boolean isThrow) throws Exception {
        UserInfo user=getUser(isThrow);
        if(null==user) return null;
        else return CacheUtil.get(BusinessInfo.class,getUser().getBusiness().getOid());
    }

    /**
     * 清除商家缓存
     */
    public static void clearBusiness(String businessOid) throws Exception {
        CacheUtil.clear(BusinessInfo.class,businessOid);
    }
    /**
     * 获取当前登录店铺
     */
    public static StoreInfo getStore() throws Exception {
        return getStore(true);
    }
    /**
     * 获取当前登录店铺
     */
    public static StoreInfo getStore(boolean isThrow) throws Exception {
        UserInfo user=getUser(isThrow);
        if(null==user) return null;
        else return CacheUtil.get(StoreInfo.class,getUser().getStore().getOid());
    }

    /**
     * 清除店铺缓存
     */
    public static void clearStore(String storeOid) throws Exception {
        CacheUtil.clear(StoreInfo.class,storeOid);
    }
    /**
     * 判断数据归属,并返回归属商家
     */
    public static BusinessInfo verifyBusiness(BusinessInfo businessInfo) throws Exception {
        if(ObjectUtil.isEmptyOid(businessInfo))
            return getBusiness();
        BusinessInfo business=getBusiness();
        if(!business.getOid().equals(businessInfo.getOid())){
            throw new MException("权限错误");
        }else{
            return business;
        }
    }
    /**
     * 判断数据归属,并返回归属店铺
     */
    public static StoreInfo verifyStore(StoreInfo storeInfo) throws Exception {
        if(ObjectUtil.isEmptyOid(storeInfo))
            return getStore();
        StoreInfo store=getStore();
        if(!store.getOid().equals(storeInfo.getOid())){
            throw new MException("权限错误");
        }else{
            return store;
        }
    }

    /**
     * 是否有权限，判断是否等于当前登陆人
     */
    public static boolean hasPower(UserInfo user) throws Exception {
        if(ObjectUtil.isEmptyOid(user)) return false;
        return getUser().getOid().equals(user.getOid());
    }
    /**
     * 是否有权限，判断是否等于当前登陆店铺
     */
    public static boolean hasPower(StoreInfo store) throws Exception {
        if(ObjectUtil.isEmptyOid(store)) return false;
        return getStore().getOid().equals(store.getOid());
    }

    /**
     * 是否有权限 满足一个即可
     */
    public static boolean hasPower(String... powers) throws Exception {
        String[] ps=getUser().getPowers();
        for(String power : powers){
            if(ArrayUtil.isContain(ps,power)){
                return true;
            }
        }
        return false;
    }
    /**
     * 判断权限 满足一个即可
     */
    public static void verifyPower(String... powers) throws Exception {
        if(!hasPower(powers)) throw new MException("权限不足");
    }

    private static final String VerifyAccountDateFormat="yyyy年MM月";
    /**
     * 验证时间是否逾期
     */
    public static void verifyAccountDate(Date date) throws Exception {
        Date d=new Date();
        int day=Integer.parseInt(DateUtil.format(d,"dd"));
        int set=Integer.parseInt(getStore().getAccountDay());
        String dateString=DateUtil.format(date,VerifyAccountDateFormat);
        if(day>=set){//账期结束日及以后
            String now=DateUtil.format(d,VerifyAccountDateFormat);
            if(!now.equals(dateString)){
                throw new MException("账期错误，请选择"+now+"的日期。");
            }
        }else{//账期结束日之前
            String now1=DateUtil.format(DateUtil.getLastMonth(d),VerifyAccountDateFormat);
            String now2=DateUtil.format(d,VerifyAccountDateFormat);
            if(!(now1.equals(dateString)||now2.equals(dateString))){
                throw new MException("账期错误，请选择"+now1+"或"+now2+"的日期。");
            }
        }
    }
}
